from rest_framework import serializers
from .models import CourseCategory,Course,Teacher,CourseChapter,CourseLesson

class CourseCategoryModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseCategory
        fields = ["id","name"]


class CourseTeacherModelSerializer(serializers.ModelSerializer):
    """课程所属老师的序列化器"""
    class Meta:
        model = Teacher
        fields = ("id","name","title", "signature","brief","image")


class CourseModelSerializer(serializers.ModelSerializer):
    """课程信息的序列化器"""
    teacher = CourseTeacherModelSerializer() # 老师 1 : 多课程
    #返回课时信息
    lesson_list = serializers.SerializerMethodField()
    # teacher = CourseTeacherModelSerializer(many=True) # 多对1
    #返回真实价格
    real_price = serializers.SerializerMethodField()
    class Meta:
        model = Course
        fields = ("id","name","course_img","students","lessons","pub_lessons","price","teacher","lesson_list","discount_name", "real_price","activity_time")

    def get_lesson_list(self, obj):
        """自定义方法 用于获取课时信息"""
        # 调用模型中的lesson_list的方法
        #  obj 当前正在序列化的模型实例
        lesson_data = obj.lesson_list()
        return lesson_data

    def get_real_price(self, obj):
        """自定义方法 用于获取真实价格"""
        return obj.real_price()



class CourseRetrieveSerializer(serializers.ModelSerializer):
    teacher = CourseTeacherModelSerializer()
    class Meta:
        model = Course
        fields = ["id","name","students","lessons","pub_lessons","price","course_img","teacher","level_name","brief_html","course_video","discount_name", "real_price","activity_time"]


class CourseLessonSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseLesson
        fields = ["id","name","duration","free_trail"]


class CourseChapterSerializer(serializers.ModelSerializer):
    coursesections = CourseLessonSerializer(many=True, read_only=True)
    class Meta:
        model = CourseChapter
        fields = ["chapter","name","summary","coursesections"]